// eslint-disable-next-line
import * as loginService from '@/api/login'
// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'

// 前端路由表 (基于动态)
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  403: () => import(/* webpackChunkName: "error" */ '@/views/exception/403'),
  404: () => import(/* webpackChunkName: "error" */ '@/views/exception/404'),
  500: () => import(/* webpackChunkName: "error" */ '@/views/exception/500'),

  // 你需要动态引入的页面组件
  statistics: () => import('@/views/dashboard/Workplace'),
  basicLayout: () => import('@/layouts/BasicLayout'),
  permissions: () => import('@/views/sys/permissions'),
  system: () => import('@/views/sys/index'),
  welcome: () => import('@/views/dashboard/Workplace'), // 数据总览
  // 用户管理
  userWithdrawals: () => import('@/views/userManagement/userWithdrawals'), // 用户提现
  userList: () => import('@/views/userManagement/userList'), // 用户列表
  adjustmentUserBalances: () => import('@/views/userManagement/adjustmentUserBalances'), // "用户余额调整"
  teamList: () => import('@/views/userManagement/teamList'), // 团队列表
  userFlowReport: () => import('@/views/userManagement/userFlowReport'), // 用户流水报表
  subscriptionStatement: () => import('@/views/userManagement/subscriptionReport'), // 认购流水报表
  teamRevenueReport: () => import('@/views/userManagement/teamRevenueReport'), // 团队收益报表
  // 订单管理
  rechargeOrders: () => import('@/views/orderManagement/rechargeOrders'), // 充值订单
  withdrawalOrders: () => import('@/views/orderManagement/withdrawalOrders'), // 提现订单

  // 配置管理
  investmentProjects: () => import('@/views/configurationManagement/investmentProjects'), // 投资项目
  teamManagement: () => import('@/views/configurationManagement/teamManagement'), // 团队管理
  vipMemberConfiguration: () => import('@/views/configurationManagement/vipMemberConfiguration'), // VIP会员配置
  bulletinConfiguration: () => import('@configView/noticeConfig'), // 公告配置
  imageConfiguration: () => import('@configView/imgConfig'), // 图片管理
  advertisementConfiguration: () => import('@configView/adConfig'), // 广告管理
  appConfiguration: () => import('@configView/appConfig'), // app配置
  rechargeMethodManagement: () => import('@configView/rechargeConfig'), // 充值方式管理
  // 后台管理
  ipWhitelisting: () => import('@/views/backOfficeManagement/ipWhitelisting'), // 后台IP白名单
  operationLog: () => import('@/views/backOfficeManagement/logManagement/actionLog.vue'), // 操作日志
  loginLog: () => import('@/views/backOfficeManagement/logManagement/loginLog.vue'), // 登录日志
  userManagement: () => import('@/views/backOfficeManagement/adminManagement'), // 管理员列表
  roleManagement: () => import('@/views/backOfficeManagement/roleManagement'), // 角色列表
  menuManagement: () => import('@/views/backOfficeManagement/menuManagement'), // 菜单管理
}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*',
  redirect: '/404',
  hidden: true,
}

// 根级菜单
const rootRouter = {
  key: '',
  name: 'index',
  path: '',
  component: 'BasicLayout',
  redirect: '/dashboard',
  meta: {
    title: '首页',
  },
  children: [],
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (res) => {
  return new Promise((resolve, reject) => {
    const routers = generator([
      {
        permissionName: '首页',
        key: '',
        permissionFile: 'BasicLayout',
        redirect: '/welcome',
        menuResponseList: res.data?.menuResponseTree,
      },
    ])
    routers.push(notFoundRouter)
    console.log(JSON.parse(JSON.stringify(routers)), ' routers ')
    resolve(routers)
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  console.log(routerMap, 'routerMap', parent)
  return routerMap.map((item) => {
    // console.log(item, 'item111')
    // const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}
    const { permissionName } = item || {}
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.permissionPath || `${(parent && parent.path) || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.permissionFile || item.key || '',
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component: constantRouterComponents[item.permissionFile],
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: permissionName,
        icon:item.permissionLog
      },
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.menuResponseList && item.menuResponseList.length > 0) {
      // Recursion
      currentRouter.children = generator(item.menuResponseList, currentRouter)
    }
    // console.log(JSON.parse(JSON.stringify(currentRouter)), 'currentRouter  ')
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
// const listToTree = (list, tree, parentId) => {
//   list.forEach((item) => {
//     console.log('item', item)
//     // 判断是否为父级菜单
//     if (item.parentPerId === parentId || parentId == 0 ) {
//       const child = {
//         ...item,
//         key: item.permissionId || item.name,
//         menuResponseList: [],
//       }
//       // 迭代 list， 找到当前菜单相符合的所有子菜单
//       listToTree(list, child.menuResponseList, item.permissionId)
//       // 删掉不存在 children 值的属性
//       if (child.menuResponseList.length <= 0) {
//         delete child.menuResponseList
//       }
//       // 加入到树中
//       tree.push(child)
//     }
//   })
// }
